<template>
  <el-dialog :modelValue="show" title="操作" top="12vh" :close-on-click-modal="false" :close-on-press-escape="false" @close="handleClose">
    <template #header>
      <span class="tipsText flex"><span class="box-title">操作</span>( <span class="mustPass">*</span>为必填,其他为选填 )</span>
    </template>
    <el-form :model="data.addQuery" class="dialogMaxHeight" ref="addQuery" :rules="data.rules" status-icon
      :validate-on-rule-change="false" :scroll-to-error="true">
      <form-item title="商户名称" :pass="true" value="agent_name">
        <el-input clearable placeholder="请输入" maxlength="20" v-model="data.addQuery.agent_name" />
        <span class="tipsText">(推广平台的名称简称)</span>
      </form-item>
      <form-item title="地区选择" :pass="true" value="area">
        <el-select v-model="data.addQuery.area" filterable placeholder="请选择">
          <el-option v-for="(item, index) in COUNTRY" :key="index" :label="item.label" :value="item.value" />
        </el-select>
        <span class="tipsText">(推广平台的地区,下拉搜索选择)</span>
      </form-item>
      <form-item title="结算货币" :pass="true" value="currency_id">
        <el-select v-model="data.addQuery.currency_id" filterable placeholder="请选择" :disabled="selectToLabel(indexStore.operatorArray, data.addQuery.operated_id,'type','value')==1?true:false">
          <el-option v-for="(item, index) in indexStore.currentArray" :key="index" :label="item.label+' ('+ item.type +')'+'-'+item.remark"
            :value="item.value" />
        </el-select>
        <span class="tipsText">(选择的货币游戏内即显示对应的货币符号)</span>
      </form-item>
      <form-item title="商户后台账号" :pass="true" value="account">
        <el-input clearable placeholder="请输入" autocomplete="off" :disabled="data.addQuery.id != 0" maxlength="20"
          v-model="data.addQuery.account" />
      </form-item>
      <form-item title="密码" :pass="data.rules.password[0].required" value="password">
        <el-input clearable placeholder="请输入" autocomplete="new-password" type="password"
          v-model="data.addQuery.password" />
      </form-item>
      <form-item title="钱包模式" :pass="true" value="api_type">
        <el-select v-model="data.addQuery.api_type" placeholder="请选择" :disabled="data.addQuery.id?true:false">
          <el-option v-for="item in APITYPE" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </form-item>
      <form-item title="商户类型" value="google_check" v-if="!indexStore.is_general_agent">
        <el-radio-group v-model="data.addQuery.agent_type" size="large">
          <el-radio-button label="正常商户" :value="0" />
          <el-radio-button label="测试商户" :value="1" />
        </el-radio-group>
        <span class="tipsText">(用于区分数据统计，测试商户不纳入数据统计)</span>
      </form-item>
      <form-item title="GGR分成比例" :pass="true" value="slot_ratio">
        <el-input clearable type="number" oninput="if(value>100 || value<0) value=0"
          v-model.number="data.addQuery.slot_ratio" placeholder="请输入0-100数字">
          <template #append>%</template>
        </el-input>
        <span class="tipsText">(参考 3%  4% 5%)</span>
      </form-item>
      <form-item title="商户游戏" value="game_ids" style="height: auto;position: relative;">
        <el-button :type="data.addQuery.gameList.length != indexStore.gameArray.length?'danger':'info'" @click="chooseGame()">{{ data.addQuery.gameList.length != indexStore.gameArray.length?'全选游戏':'取消全选' }}</el-button>
        <el-checkbox-group v-model="data.addQuery.gameList">
          <el-checkbox class="margin5" v-for="(item,index) in indexStore.gameArray" :key="index" :value="item.value" border>
            <div class="flexCenter">
              <img class="game-icon" :src="selectToLabel(GAMEICON, item.value)" alt="">
              {{ selectToLabel(indexStore.gameArray,item.value) }}
            </div>
          </el-checkbox>
        </el-checkbox-group>
      </form-item>
      <form-item title="商户秘钥" :pass="data.rules.key[0].required" value="key">
        <div class="inputAndBtn">
          <el-input clearable placeholder="请输入" v-model="data.addQuery.key" />
          <el-button class="marginL5" size="small" type="primary" @click="autoKey">生成秘钥</el-button>
          <span class="tipsText">(非必填-该秘钥为商户填写，总代账号只做展示和修改)</span>
        </div>
      </form-item>
      <form-item title="第三方接口域名" :pass="data.rules.domain_name[0].required" value="domain_name">
        <el-input class="width320" clearable placeholder="请输入" v-model="data.addQuery.domain_name">
          <template #prepend>https://</template>
        </el-input>
        <span class="tipsText">(非必填-该地址为商户填写，总代账号只做展示和修改)</span>
      </form-item>
      <form-item title="备注" value="remark">
        <el-input clearable maxlength="200" type="textarea" :checkedItems="3" placeholder="请输入"
          v-model="data.addQuery.remark" />
        <span class="tipsText">(非必填)</span>
      </form-item>
      <form-item title="登陆谷歌验证" value="google_check">
        <el-radio-group v-model="data.addQuery.google_check" size="large"  @change="chooseGoogle">
          <el-radio-button label="不验证" :value="0" />
          <el-radio-button label="验证" :value="1" />
        </el-radio-group>
        <span class="tipsText">(非必选)</span>
      </form-item>
      <form-item title="谷歌Url" value="google_url" v-show="data.addQuery.google_check" style="height:auto">
        <QrcodeVue :value="data.addQuery.google_url" :size="140" fg-color="#000" />
        <el-input class="width100 marginT5" v-model="data.addQuery.google_url" type="text" readonly />
      </form-item>
      <form-item title="谷歌秘钥" value="google_secret" v-show="data.addQuery.google_check">
        <el-input class="marginT5" v-model="data.addQuery.google_secret" type="text" readonly />
      </form-item>
      <form-item title="谷歌验证码"  :pass="props.checkedItem.google_check || data.addQuery.google_check?true:false" value="google_code" v-show="props.checkedItem.google_check || data.addQuery.google_check">
        <el-input class="marginT5" v-model="data.addQuery.google_code" type="text" placeholder="请输入谷歌验证码" />
      </form-item>
      <form-item title="登陆IP白名单" value="white_ip">
        <el-input clearable maxlength="200" type="textarea" :checkedItems="3" placeholder="请输入登陆IP白名单,多个IP用( ; )分开"
          v-model="data.addQuery.white_ip" />
        <span class="tipsText">(非必填)</span>
      </form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import FormItem from '@/components/FormItem/FormItem.vue'
import { DEMOPLAY, APITYPE,GAMEICON } from '@/config/eunm'
import { COUNTRY } from '@/config/country'
import QrcodeVue from 'qrcode.vue'
import { throttle, selectToLabel,removeDomain,domainVerification } from '@/utils/index'
import { postSystemaddAgent, putSystemChangeAgent, postSystemFandKey, googleKey } from '@/api/merchant'
import { useStore } from '@/stores/index'
const indexStore = useStore()

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  checkedItem: {
    type: Object,
    default: () => { }
  }
})

watch(
  () => [props.checkedItem,props.show],
  async (value) => {
    if(value[0]){
      Object.assign(data.addQuery,value[0])
      data.addQuery.domain_name=removeDomain(data.addQuery.domain_name)
    }else{
      chooseGame()
    }
    data.rules.password[0].required = data.addQuery.id ? false:true
    data.rules.key[0].required = data.addQuery.key ? true:false
    data.rules.domain_name[0].required = data.addQuery.domain_name ? true:false
  }
)

const data = reactive({
  addQuery: {
    id: 0, // 商户id
    operated_id: 0, // 商户上级ID
    agent_name: '', //商户名称
    area: '', //地区选择
    client_lang: '', // 语言选择 字符串
    key: '', // 秘钥
    currency: '', // 货币
    currency_id: 1, // 货币
    agent_type: 0, // 商户类型
    account: '', // 商家后台账号
    password: '', // 密码
    api_type: '', // api接入模式
    agent_request_url: '', // 商户请求地址
    domain_name: '', // 第三方接口域名
    remark: '', // 备注
    game_ids: '', // 商户游戏
    gameList: [] as any[], // 商户游戏
    white_ip: '', // IP白名单
    google_check: 0, // IP白名单
    google_url: '', // 谷歌二维码
    google_secret: '', // 谷歌二维码
    google_code: '', // 谷歌验证码
    slot_ratio: null, // slot 分成比例 百分比
    hundred_ratio: null, // 百人 分成比例 百分比
    fish_ratio: null, // 捕鱼 分成比例 百分比
    street_ratio: null // 街机 分成比例 百分比
  },
  rules: {
    agent_name: [{ required: true, message: '请输入', trigger: 'blur' }],
    area: [{ required: true, message: '请选择', trigger: 'change' }],
    currency: [{ required: true, message: '请选择', trigger: 'change' }],
    account: [{ required: true, message: '请输入', trigger: 'blur' }],
    password: [
      { required: true, message: '请输入', trigger: 'blur' },
      { min: 6, max: 20, message: '请输入6-20位字符', trigger: 'blur' }
    ],
    api_type: [{ required: true, message: '请选择', trigger: 'change' }],
    slot_ratio: [{ required: true, message: '请输入0-100数字', trigger: 'blur' }],
    domain_name: [{ required: false, message: '请输入', trigger: 'blur' }],
    key: [{ required: false, message: '请输入', trigger: 'blur' }],
  },
  loading: false
})


// 保存
const addQuery = ref<FormInstance>()
const save = throttle(async () => {
  if (!addQuery.value) return
  await addQuery.value.validate(async (valid, fields) => {
    if (valid) {
      let query = JSON.parse(JSON.stringify(data.addQuery))
      data.loading = true
      query.game_ids = query.gameList.join(',')
      query.hundred_ratio = query.fish_ratio = query.street_ratio = query.slot_ratio
      try {
        if(props.checkedItem.google_check && !query.google_code){
          return ElMessage({ message: '请输入谷歌验证码', type: 'error' })
        }else if(!props.checkedItem.google_check && !query.google_check){
          query.google_code = 0
          query.google_url = ''
          query.google_secret = ''
        }else if(query.google_check && !query.google_code){
          return ElMessage({ message: '请输入谷歌验证码', type: 'error' })
        }else if(query.google_code){
          query.google_code = Number(query.google_code)
        }
        query.currency = selectToLabel(indexStore.currentArray,query.currency_id)
        // 域名格式校验
        query.domain_name = domainVerification(query.domain_name)
        const res = query.id ? await putSystemChangeAgent(query) : await postSystemaddAgent(query)
        data.loading = false
        if(res.code){
          ElMessage({
            message: '操作成功',
            type: 'success'
          })
          indexStore.getAgent() //商户汇总
          indexStore.getAgentCurrency() //商户货币汇总
          query = null
          handleClose(true)
        }
      } catch (err) {
        data.loading = false
      }
    }
  })
}, 3000)

// 是否开启谷歌验证码
const chooseGoogle = async (val: number) => {
  if (val) {
    if (!data.addQuery.agent_name) {
      data.addQuery.google_check = 0
      return ElMessage({
        type: 'error',
        message: '请输入商户名称'
      })
    }else{
      if(data.addQuery.google_url) return 
      let res = await googleKey({ username: data.addQuery.agent_name })
      data.addQuery.google_url = res.data.google_url
      data.addQuery.google_secret = res.data.google_secret
    }
  }
}

// 游戏配置
const chooseGame = () => {
  if(data.addQuery.gameList.length != indexStore.gameArray.length){
    data.addQuery.gameList = []
    indexStore.gameArray.forEach((item:any)=>{
      return data.addQuery.gameList.push(Number(item.value))
    })
  }else{
    data.addQuery.gameList = []
  }
}

// 生成秘钥
const autoKey = async () => {
  let res = await postSystemFandKey({})
  data.addQuery.key = res.data
}

// 取消
const emit = defineEmits(['cancel'])
const handleClose = async (val?: Boolean) => {
  emit('cancel', val)
  addQuery.value!.resetFields()
  data.addQuery = {
    id: 0, // 商户id
    operated_id: 0, // 商户上级ID
    agent_name: '', //商户名称
    area: '', //地区选择
    client_lang: '', // 语言选择 字符串
    key: '', // 秘钥
    currency: '', // 货币
    currency_id: 0, // 货币
    agent_type: 0, // 商户类型
    account: '', // 商家后台账号
    password: '', // 密码
    api_type: '', // api接入模式
    agent_request_url: '', // 商户请求地址
    domain_name: '', // 第三方接口域名
    remark: '', // 备注
    game_ids: '', // 商户游戏
    gameList: [], // 商户游戏
    white_ip: '', // IP白名单
    google_check: 0, // IP白名单
    google_url: '', // 谷歌二维码
    google_secret: '', // 谷歌二维码
    google_code: '', // 谷歌二维码
    slot_ratio: null, // slot 分成比例 百分比
    hundred_ratio: null, // 百人 分成比例 百分比
    fish_ratio: null, // 捕鱼 分成比例 百分比
    street_ratio: null // 街机 分成比例 百分比
  }
}
</script>
<style scoped lang="scss">
.inputAndBtn {
  display: flex;
  align-items: center;
}
</style>
